package LeetCode.leetcode116;

import java.util.*;

class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {
    }

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
}

class Solution {
    public Node connect(Node root) {
        if (root == null)
            return root;
        Node tmp;
        Queue<Node> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            List<Node> lines = new ArrayList<>();
            int length = queue.size();
            while (length > 0){
                tmp = queue.poll();
                lines.add(tmp);
                //只用判断左子树，因为是满二叉树
                //到达最后一层，一旦为空，同层节点就不用再次判断了
                if (tmp.left != null){
                    queue.offer(tmp.left);
                    queue.offer(tmp.right);
                }
                length--;
            }
            //将root的next置零
            if (lines.size() == 1){
                lines.get(0).next = null;
            }else {
                for (int i = 0; i < lines.size()-1; i++) {
                    lines.get(i).next = lines.get(i+1);
                }
                //最后一个值为null
                lines.get(lines.size()-1).next = null;
            }
        }
        return root;
    }
}
